import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:lighthouse/index.dart';

class OtherSettingsPage extends StatefulWidget {
  const OtherSettingsPage({Key? key}) : super(key: key);

  @override
  State<OtherSettingsPage> createState() => _OtherSettingsPageState();
}

class _OtherSettingsPageState extends State<OtherSettingsPage> {
  //  缓存大小
  var _cacheSizeStr = '';

  //  是否为最新版本
  final bool _currentVersionShow = false;

  @override
  void initState() {
    ///计算缓存大小
    loadCache();

    super.initState();
  }

  ///当前版本更新
  _currentVersion() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            // title: const Text('更新版本'),
            content: const Text('当前版本不是最新版本，是否升级为v1.0.1'),
            actions: <Widget>[
              TextButton(
                child: const Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop('cancel');
                },
              ),
              TextButton(
                child: const Text('确认'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  ///计算缓存大小
  Future<void> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    //打印每个缓存文件的路径
    // tempDir.list(followLinks: false,recursive: true).listen((file){
    //   print(file.path);
    // });
    // print('临时目录大小: ' + value.toString());
    setState(() {
      _cacheSizeStr = _renderSize(value); // _cacheSizeStr用来存储大小的值
    });
  }

  _renderSize(double? value) {
    if (value == null) {
      return 0;
    }
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value! > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  ///清除缓存
  _clearCache() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            // title: const Text('清除缓存'),
            content: Text('是否清除app缓存，当前缓存$_cacheSizeStr'),
            actions: <Widget>[
              TextButton(
                child: const Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop('cancel');
                },
              ),
              TextButton(
                child: const Text('确认'),
                onPressed: () {
                  _clearCaches();
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  void _clearCaches() async {
    //此处展示加载loading
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
      await delDir(tempDir);
      await loadCache();
      showToast("清除缓存成功");
    } catch (e) {
      debugPrint(e.toString());
      showToast('清除缓存失败');
    } finally {
      //此处隐藏加载loading
    }
  }

  ///递归方式删除目录
  Future<void> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        total += await _getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon:
                  Image.asset('images/common_left.png', width: 16, height: 16),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            title: const Text('其他设置'),
            centerTitle: true,
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Expanded(child: _buildMenus()), //构建功能菜单
            ],
          ), // 构建主页面
        ),
      ),
    );
  }

  /// label 标题
  /// value 值
  /// rightIoc 是否显示右侧图标
  /// fu 点击回调
  Widget _buildMenu(label, value, rightIoc, fu) {
    ThemeData themeData = Theme.of(context);
    return GestureDetector(
      onTap: fu,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.fromLTRB(17, 20, 17, 20),
        decoration: BoxDecoration(
          color: themeData.colorScheme.background,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(label,
                style: themeData.textTheme.titleMedium
                    ?.copyWith(color: themeData.colorScheme.onBackground)),
            Row(
              children: [
                Text(value,
                    style: themeData.textTheme.bodyMedium
                        ?.copyWith(color: themeData.colorScheme.onSecondary)),
                const SizedBox(width: 10),
                rightIoc
                    ? Image.asset(
                        'images/common_right.png',
                        width: 17,
                        height: 17,
                      )
                    : const SizedBox(width: 10),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _sizeBox() {
    return SizedBox(
      width: double.infinity,
      height: 1,
      child: DecoratedBox(
        decoration: BoxDecoration(color: Theme.of(context).colorScheme.surface),
      ),
    );
  }

  // 构建菜单项
  Widget _buildMenus() {
    return Consumer<UserModel>(
      builder: (BuildContext context, UserModel userModel, Widget? child) {
        var s = S.of(context);
        return Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surface,
          ),
          child: ListView(
            children: [
              const SizedBox(height: 10),
              // _buildMenu(s.theme, '', true,
              //     () => Navigator.pushNamed(context, "themes")),
              _sizeBox(),
              _buildMenu(s.language, '', true,
                  () => Navigator.pushNamed(context, "language")),
              _sizeBox(),
              _buildMenu(s.settingsTextScaling, '', true,
                  () => Navigator.pushNamed(context, "fontSize")),
              _sizeBox(),
              _buildMenu(s.darkMode, '', true,
                  () => Navigator.pushNamed(context, "darkMode")),
              _sizeBox(),
              _buildMenu('当前版本', '1.0.0', true, () {
                _currentVersionShow ? _currentVersion() : showToast("当前为最新版本");
              }),
              _sizeBox(),
              _buildMenu('清除缓存', _cacheSizeStr, true, _clearCache)
            ],
          ),
        );

        //     ListView(
        //       children: <Widget>[
        //         const AboutListTile(
        //           icon: Icon(Icons.account_circle),
        //           child: Text('关于我们'),
        //           applicationName: '路灯之家',
        //           applicationVersion: 'V1.0.0',
        //           applicationIcon: Icon(Icons.account_circle),
        //           applicationLegalese: '国信天宇网络技术有限公司',
        //         )
        //       ],
        //     );
      },
    );
  }
}
